【Pybind11 C++调用Python并返回结果】 | 您所在的位置:网站首页 › pybind11 传递对象指针 › 【Pybind11 C++调用Python并返回结果】 |
网上有很多CPP用Pybind11生成pyd的的代码,很少有CPP直接调用python的(想看py调用CPP的看https://www.jianshu.com/p/9619f8f02891,归纳的很全了) 这里简单介绍一下 首先,如果系统已经有最新的默认python3x64,那么直接使用这个的dll,lib以及环境变量,如果没有设置环境变量,那么自己百度里谷歌一下,因为这好像是一个bug,调用py的dll会搜索python的环境变量;如果没有安装,那么更好,直接下载python3.x 64bit,具体版本可以看Pybind11支持的最高版本,并且设置环境变量(一般安装python会有设置环境变量的勾选) PS:32bit的自己想办法,什么年代了还用这个呢 然后Pybind11是支持C++11的,我们用VS2019+Win10x64开发 这里其实用python原生的C++api也可以,但是麻烦一点,底层应该都是一样 Pybind11已经帮我们做好了 show me the code! #include #include #include #include // everything needed for embedding #include namespace py = pybind11; using namespace std; //C:\Users\23607\AppData\Local\Programs\Python\Python37\ //https://blog.csdn.net/mvp_Dawn/article/details/102535495 /*python3启动失败 Fatal Python error : initfsencoding: unable to load the file system codec*/ //使用主环境默认版本python和其环境变量以及dll //Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 int main() { py::scoped_interpreter python; py::module sys = py::module::import("sys"); py::print(sys.attr("path")); py::module t = py::module::import("tttt"); py::object result; try { result = t.attr("add")(1, 2); } catch (std::exception& e) { cout int len = WideCharToMultiByte(type, 0, wch, -1, nullptr, 0, nullptr, nullptr); char* str = new char[len + 1]; memset(str, 0, len + 1); WideCharToMultiByte(type, 0, wch, -1, str, len, nullptr, nullptr); return str; } //C:\Users\23607\AppData\Local\Programs\Python\Python37\ //https://blog.csdn.net/mvp_Dawn/article/details/102535495 /*python3启动失败 Fatal Python error : initfsencoding: unable to load the file system codec*/ //使用主环境默认版本python和其环境变量以及dll //Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 int main() { py::scoped_interpreter python; py::module sys = py::module::import("sys"); py::print(sys.attr("path")); py::module t = py::module::import("imouto"); py::object result; try { auto func = t.attr("process_str"); string inStr = "imouto is love";//"妹妹就是爱love"; auto xxb = trans(L"imouto is love爱", 65001); auto len = strlen(xxb);//inStr.size(); const unsigned char* ss = (const unsigned char*)xxb;//(const unsigned char*) (inStr.c_str()); int* ss_copy = new int[len+1]; std::copy(ss,ss + len, ss_copy); //for (size_t i = 0; i < len; i++) //{ // printf("%d ", ss_copy[i]); //} //printf("\n"); ss_copy[len] = (int)'\0'; vector inDataShape = { (int)(len + 1) }; // construct numpy array py::array_t npInputArray(inDataShape, ss_copy); result = func(npInputArray); delete[]ss_copy; } catch (std::exception& e) { cout |
CopyRight 2018-2019 实验室设备网 版权所有 |